import os
import re
import shutil
import time

import jwt
from django.core.mail import send_mail

from Files.models import File
from Master.models import Master
from User.models import User
from Util import verify_token, back_failed, back_success
from server import settings


def validate_token(request):
    res = verify_token(request)
    if not res:
        return back_success("false")
    else:
        return back_success("true")


def login(request):
    try:
        password = request.POST.get("password")
        email = request.POST.get("email")
        if not password:
            return back_failed("参数错误")
        if not email:
            return back_failed("参数错误")
        user = User.objects.get(email=email, password=password)
        token = str(jwt.encode({
            "timestamp": str(time.time()),
            "email": user.email,
            "password": user.password,
            "nickname": user.nickname,
        }, settings.SECRET_KEY, algorithm="HS256"))
        if "b'" in token:
            token = re.findall("\'(.*?)\'", token)[0]
        User.objects.filter(email=email, password=password).update(token=token)
        return back_success(token)
    except Exception as e:
        return back_failed("API异常" + str(e))


def register(request):
    try:
        password = request.POST.get("password")
        email = request.POST.get("email")
        if not password:
            return back_failed("参数错误")
        if not email:
            return back_failed("参数错误")
        if User.objects.filter(email=email).exists():
            return back_failed("账号已存在")
        else:
            User.objects.create(
                email=email,
                password=password
            )
            # 赠送默认背景和字体
            File.objects.create(
                email=email,
                path="assets/font/default.ttf",
                filetype="font",
                name="default.ttf"
            )
            File.objects.create(
                email=email,
                path="assets/font/default1.ttf",
                filetype="font",
                name="default1.ttf"
            )
            File.objects.create(
                email=email,
                path="assets/images/default_background.png",
                filetype="images",
                name="default_background.png"
            )
            return back_success("注册成功")
    except Exception as e:
        return back_failed("API异常" + str(e))


def reset_password(request):
    res = verify_token(request)
    if not res:
        return back_failed("登录状态失效，请重新登录")
    else:
        try:
            new_password = request.POST.get("password")
            email = res["email"]
            if not new_password:
                return back_failed("参数错误")
            if not email:
                return back_failed("参数错误")
            u = User.objects.filter(email=email)
            if not u.exists():
                return back_failed("账号不存在")
            else:
                u.update(password=new_password)
                return back_success("修改成功")
        except Exception as e:
            return back_failed("API异常" + str(e))


def sendEmail(request):
    import random
    yzm = ""
    for i in range(4):
        j = random.randrange(0, 4)
        if j == 1:
            a = random.randrange(0, 10)
            yzm = yzm + str(a)
        elif j == 2:
            a = chr(random.randrange(65, 91))
            yzm = yzm + a
        else:
            a = chr(random.randrange(97, 127))
            yzm = yzm + a
    try:
        email = request.POST.get("email")
        if not email:
            return back_failed("参数错误")
        a = send_mail('验证码', '您的验证码是:' + str(yzm), settings.EMAIL_HOST_USER, [email])
        if a == 1:
            return back_success(yzm)
        else:
            return back_success("发送失败")
    except Exception as e:
        return back_failed("API异常" + str(e))


def update_profile(request):
    res = verify_token(request)
    if not res:
        return back_failed("登录状态失效，请重新登录")
    else:
        try:
            nickname = request.POST.get("nickname")
            email = res["email"]
            if not nickname:
                return back_failed("参数错误")
            if not email:
                return back_failed("参数错误")
            u = User.objects.filter(email=email)
            if not u.exists():
                return back_failed("账号不存在")
            else:
                user = u.first()
                token = str(jwt.encode({
                    "timestamp": str(time.time()),
                    "email": user.email,
                    "password": user.password,
                    "nickname": nickname,
                }, settings.SECRET_KEY, algorithm="HS256"))
                if "b'" in token:
                    token = re.findall("\'(.*?)\'", token)[0]
                u.update(token=token, nickname=nickname)
                return back_success(token)
        except Exception as e:
            return back_failed("API异常" + str(e))


def delete_account(request):
    res = verify_token(request)
    if res is not False:
        return back_failed("登录状态失效，请重新登录")
    else:
        email = res["email"]
        if not email:
            return back_failed("参数错误")
        u = User.objects.filter(email=email)
        if not u.exists():
            return back_failed("账号不存在")
        else:
            # 删除账号和文件
            u.delete()
            files = File.objects.filter(email=email)
            for f in files:
                if not "default_background.png" in f.path and not "default.ttf" in f.path and not "default1.ttf" in f.path:
                    os.remove(f.path)  # 删除images,font
            files.delete()
            # 删除作品和临时文件夹
            if os.path.exists("assets" + os.sep + "master" + os.sep + email):
                shutil.rmtree("assets" + os.sep + "master" + os.sep + email)
            if os.path.exists("assets" + os.sep + "temp" + os.sep + email):
                shutil.rmtree("assets" + os.sep + "temp" + os.sep + email)
            Master.objects.filter(email=email).delete()
            return back_success("注销成功")
